import React, { useEffect, useState } from "react";
import NavBar from "@/components/NavBar/NavBar";
import { Button, Empty, Tabs, Tag, Toast } from "antd-mobile";
import OrderItem from "@/components/OrderItem/OrderItem";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { cancelOrderThunk, fetchOrderListThunk } from "@/store/modules/orderStore";
import type { OrderParams } from "@/type/OrderType";
import "./Order.scss";

const Order = () => {
   const navigate = useNavigate();

   const enhanceDispatch = useEnhanceDispatch();

   const [searchParams] = useSearchParams();

   const orderType = searchParams.get("orderType");

   const orderList = useEnhanceSelector(state => state.orderStore.orderList);

   const [params, setParams] = useState<OrderParams>({
      page: 1,
      dataType: orderType as string,
   });


   /**
    * @description 获取订单列表的回调函数函数
    * */
   const fetchOrderList = async () => {
      try {
         await enhanceDispatch(fetchOrderListThunk(params));
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    *
    *@description 修改激活项的回调函数
    * */
   const changeActiveTab = (activeTab: string) => {
      setParams({ ...params, dataType: activeTab });
   };

   /**
    * @description 点击取消订单按钮的回调函数
    * */
   const handleCancel = async (order_id: number) => {
      try {
         const content = await enhanceDispatch(cancelOrderThunk(order_id)).unwrap();
         Toast.show({ icon: "success", content });
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   const renderOrderStatus = (order_status: number, order_id: number) => {
      if (order_status === 21) {
         return <Tag>取消申请中</Tag>;
      } else if (order_status === 10) {
         return <Button color="primary" size="mini" onClick={() => handleCancel(order_id)}>取消订单</Button>;
      } else if (order_status === 30) {
         return <Tag>已完成</Tag>;
      } else if (order_status === 20) {
         return <Tag>取消</Tag>;
      }
   };

   const renderOrderList = () => {
      if (orderList.length) {
         return (
            orderList.map((order, index) => {
               return (
                  <div className="card" key={index}>
                     <div className="order-date">
                        <div className="date">{order.create_time}</div>
                        <div className="status">{order.state_text}</div>
                     </div>
                     <div key={index}>
                        {order.goods.map((good, index) => <OrderItem order={good} key={index}></OrderItem>)}
                        <div className="order-status">{renderOrderStatus(order.order_status, order.order_id)}</div>
                     </div>
                  </div>
               );
            })
         );
      } else {
         return (
            <div className="lazy-loading">
               <Empty description="暂无数据"></Empty>
            </div>
         );
      }
   };

   useEffect(() => {
      fetchOrderList();
   }, [params]);

   return (
      <div className="order-container">
         <div className="order-header">
            <NavBar children="订单列表" backIcon onBack={() => navigate(-1)}></NavBar>
            <Tabs activeKey={params.dataType} onChange={changeActiveTab}>
               <Tabs.Tab title="全部订单" key="all"></Tabs.Tab>
               <Tabs.Tab title="待支付" key="payment"></Tabs.Tab>
               <Tabs.Tab title="待发货" key="delivery"></Tabs.Tab>
               <Tabs.Tab title="待收货" key="received"></Tabs.Tab>
               <Tabs.Tab title="待评价" key="comment"></Tabs.Tab>
            </Tabs>
         </div>
         <div className="order-list">
            {
               renderOrderList()
            }
         </div>
      </div>
   );
};

export default Order;
